package message.preset;

import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

import message.AbstractMessageBuilder;
import message.GenericMessageBuilderSupplier;
import message.MessageBuilder;
import message.MessageBuilderSupplier;
import message.util.Step;

public class ArrayMessageBuilderSupplier implements GenericMessageBuilderSupplier{

	@Override
	public MessageBuilderSupplier wrapGeneric(MessageBuilderSupplier[] suppliers) {
		return new MessageBuilderSupplier() {
			@Override
			@SuppressWarnings("unchecked")
			public MessageBuilder get(Consumer<? super Object> callback) {
				return new AbstractMessageBuilder(callback) {
					private int length;
					private MessageBuilder[] supplier;
					private int p = 0;
					private Step step = new Step();
					{
						build = new ArrayList<Object>();
					}
					@Override
					public boolean read(ByteBuffer byteBuffer) {
						if(step.is(0)) {
							try {
								length = byteBuffer.getInt();
							} catch (BufferUnderflowException e) {
								return false;
							}
							supplier = new MessageBuilder[length];
							var s = suppliers[0];
							for(int i = 0; i<length; i++) {
								supplier[i] = s.get((x) -> {
									((List<Object>) build).add(x);
									p++;
								});
							}
							step.done();
						}
						if(step.is(1)) {
							while(p < length) {
								if(!(supplier[p].read(byteBuffer))) return false;
							}
							step.done();
						}
						
						return super.read(byteBuffer);
					}
				};
			}
		};
	}

	@Override
	public MessageBuilder get(Consumer<? super Object> callback) {
		return null;
	}
	
}
